package edu.hawaii.duedates.web.page.display;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.PropertyModel;
import edu.hawaii.duedates.DueDates.SortType;
import edu.hawaii.duedates.book.Book;
import edu.hawaii.duedates.library.Library;
import edu.hawaii.duedates.web.page.DueDatesPage;

/**
 * The display page for this DueDates-Omaomao application.
 * 
 * @author Ronn Reeves.
 */
public class Display extends DueDatesPage {
  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /**
   * Creates a new instance of the home page for DueDates-Omaomao.
   */
  public Display() {
    // Create the menu.
    createMenu();
    
    // Create the library listing.
    createLibraryListing();
    
    // Create the query results listing.
    createBooksListing();
  }

  /**
   * Creates the menu for the DueDates page.
   */
  private void createMenu() {
    this.loginLink.setEnabled(Boolean.FALSE);
    this.loginLink.setVisible(Boolean.FALSE);

    this.displayLink.setEnabled(Boolean.FALSE);
    this.displayLink.setVisible(Boolean.TRUE);
    add(this.displayLink);
    
    this.alertsLink.setEnabled(Boolean.TRUE);
    this.alertsLink.setVisible(Boolean.TRUE);
    add(this.alertsLink);  

    this.logoutLink.setEnabled(Boolean.TRUE);
    this.logoutLink.setVisible(Boolean.TRUE);
    this.logoutLink.add(this.logoutText);
    add(this.logoutLink);
  }
  
  /**
   * Creates the library listing. 
   */
  private void createLibraryListing() {
    add(new Label("wuxQueryError", getErrorMessage()));
    
    // Create the update form for accessing this user's libraries.
    Form form = new Form("wuxLibraryForm"); 

    // Add the form elements.
    String title = "Libraries for " + getDueDates().getUser().getName();
    form.add(new Label("wuxLibraryListingLabel", title));

    // Create a dataview to display the libraries in this instance.
    ListDataProvider libraries = new ListDataProvider(getDueDates().getLibraries());
    
    DataView libraryList = new DataView("wuxLibraries", libraries) { 
      /** For serialization. */
      private static final long serialVersionUID = 1L;
      
      /**
       * Display each row in the table.
       * @param item The library.
       */
      @Override
      protected void populateItem(Item item) {
        // Create the login form for accessing this user's libraries.
        final Library library = (Library) item.getModelObject();
        item.add(new Label("wuxLibraryLabel", library.getName()));
        int within = 0;
        item.add(new TextField("wuxWithin", new PropertyModel(getDueDates(), "within")));
        setWithin(within);
        item.add(new Button("wuxQueryCommand") {
          /** Support serialization. */
          private static final long serialVersionUID = 1L;
        
          /** Query the selected libraries. */
          @Override
          public void onSubmit() {
            // BEGIN REPLACE THIS CODE WITH WORKING PRODUCTION CODE---------------------------
            // Create demo list of books
            List<Book> books = new ArrayList<Book>();
            Calendar cal1 = Calendar.getInstance();
            cal1.set(2009, Calendar.FEBRUARY, 14);
            Calendar cal2 = Calendar.getInstance();
            cal2.set(2009, Calendar.JANUARY, 31);
            Calendar cal3 = Calendar.getInstance();
            cal3.set(2008, Calendar.DECEMBER, 31);
            Book dummy1 = new Book("Wicket Inaction", cal1, library.getName());
            Book dummy2 = new Book("Due Dates: The Death of Library Fees", cal2, library.getName());
            Book dummy3 = new Book("Hackystat SICU:  Pulling the Plug", cal3, library.getName());
            books.add(dummy1);
            books.add(dummy2);
            books.add(dummy3);
            setLibrary(library);
            try {
              getDueDates().requestInfo();
            }
            catch (Exception e) {
              getDueDates().setBooks(books);
            }
            // END REPLACE THIS CODE WITH WORKING PRODUCTION CODE-----------------------------
            setResponsePage(new Display());
          }
        });
      }      
    };
    form.add(libraryList);
    add(form);
  }

  /**
   * Creates the books listing. 
   */
  private void createBooksListing() {
    /** DueDate sorting link. */
    add(new Link("DueDateLink") {
      private static final long serialVersionUID = 1L;

      /** Redirects to the display page for due dates sorting. */
      @Override
      public void onClick() {
        if (getDueDates().getBooks().size() > 0) {
          getDueDates().sort(SortType.DUE_DATE);
          setResponsePage(new Display());
        }
      }
    });

    /** Title sorting link. */
    add(new Link("TitleLink") {
      private static final long serialVersionUID = 1L;

      /** Redirects to the display page for due dates sorting. */
      @Override
      public void onClick() {
        if (getDueDates().getBooks().size() > 0) {
          getDueDates().sort(SortType.TITLE);
          setResponsePage(new Display());
        }
      }
    });

    /** Library sorting link. */
    add(new Link("LibraryLink") {
      private static final long serialVersionUID = 1L;

      /** Redirects to the display page for due dates sorting. */
      @Override
      public void onClick() {
        if (getDueDates().getBooks().size() > 0) {
          getDueDates().sort(SortType.LIBRARY);
          setResponsePage(new Display());
        }
      }
    });

    Boolean hasBooks = (getDueDates().getBooks() != null) && !(getDueDates().getBooks().isEmpty());
    if (hasBooks) {
      // Create a dataview to display the books in this instance.
      ListDataProvider books = new ListDataProvider(getDueDates().getBooks());
      
      DataView bookList = new DataView("wuxBookListing", books) { 
        /** For serialization. */
        private static final long serialVersionUID = 1L;
        
        /**
         * Display each row in the table.
         * @param item The library.
         */
        @Override
        protected void populateItem(Item item) {
          // Create the list of books.
          final Book book = (Book) item.getModelObject();
          item.add(new Label("wuxDueDate", String.format(Locale.US, "%tD", book.getDueDate())));
          String title = book.getTitle();
          if (title.length() > 40) {
            title = title.substring(0, 39); 
          }
          item.add(new Label("wuxTitle", title));
          String libName = book.getLibrary();
          if (libName.length() > 16) {
            libName = libName.substring(0, 15);
          }
          item.add(new Label("wuxBookLibrary", libName));
        }
      };
      add(bookList);
    }
    
    else {
      // Create a dataview to display the books in this instance.
      ListDataProvider books = new ListDataProvider(new ArrayList<Book>());
      
      DataView bookList = new DataView("wuxBookListing", books) { 
        /** For serialization. */
        private static final long serialVersionUID = 1L;
        
        /**
         * Display each row in the table.
         * @param item The library.
         */
        @Override
        protected void populateItem(Item item) {
          // Create the login form for accessing this user's libraries.
          item.add(new Label("wuxDueDate", ""));
          item.add(new Label("wuxTitle", ""));
          item.add(new Label("wuxBookLibrary", ""));
        }      
      };
      add(bookList);
    }
  }
}
